package com.itcoon.cloud.framework.utils;

import com.itcoon.cloud.framework.constants.CommonCoreConstants;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 *
 *
 * @author Athric Yu
 * 2024/9/25
 **/
public class MethodUtil {

   public static String formatGetterName(String attribute) {
        return formatGetterName(attribute, false);
    }

    public static String formatGetterName(String attribute, boolean isBoolPrimitive) {
        return (isBoolPrimitive ? CommonCoreConstants.IS_GETTER_PREFIX : CommonCoreConstants.GETTER_PREFIX) + attribute.substring(0, 1).toUpperCase() + attribute.substring(1);
    }

    public static String formatSetterName(String attribute) {
        return CommonCoreConstants.SETTER_PREFIX + attribute.substring(0, 1).toUpperCase() + attribute.substring(1);
    }

    public static boolean isPropertyMethod(Method method){
        return !Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().equals(Object.class) && CommonCoreConstants.GETTER_SETTER_PREFIX_LIST.stream().anyMatch(prefix-> method.getName().startsWith(prefix));
    }

    public static boolean isGetter(Method method){
        return isPropertyMethod(method) && !method.getName().startsWith(CommonCoreConstants.SETTER_PREFIX);
    }

    public static boolean isSetter(Method method){
        return isPropertyMethod(method) && method.getName().startsWith(CommonCoreConstants.SETTER_PREFIX);
    }

    public static String getMethodAttribute(Method method) {
        if(isPropertyMethod(method)){
            String methodName = method.getName();
            int index = 3;
            if(method.getReturnType().equals(boolean.class) && methodName.startsWith(CommonCoreConstants.IS_GETTER_PREFIX)){
                index = 2;
            }
            boolean nextUpperFlag =  Character.isUpperCase(methodName.charAt(index + 1));
            return  (nextUpperFlag ? methodName.charAt(index) : methodName.substring(index, index + 1).toLowerCase()) + methodName.substring(index + 1);
        }
        return null;
    }
}
